﻿using AutoMapper;
using Comm100.Application.Services;
using Comm100.Framework.Auditing;
using Comm100.Framework.Authorization;
using Comm100.Public.Audit;
using Bot.Application.Dto;
using Bot.Application.Services;
using Bot.Domain.Bo;
using Bot.Domain.Entities;
using Bot.Domain.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
using Bot.Domain;
using System.Linq;
using Newtonsoft.Json;
using Comm100.Framework.Exceptions;

namespace Bot.Application.PrebuiltEntities.Service
{
    public class PrebuiltEntityAppService : BaseAppService, IPrebuiltEntityAppService
    {
        private IPrebuiltEntityDomainService _prebuiltDomainService;
        private IEntityDomainService _entityDomainService;
        private IChatbotDomainService _botDomainService;
        public PrebuiltEntityAppService(IPrebuiltEntityDomainService domainService,
            IEntityDomainService entityDomainService,
            IChatbotDomainService botDomainService) : base()
        {
            this._prebuiltDomainService = domainService;
            this._entityDomainService = entityDomainService;
            this._botDomainService = botDomainService;
        }

        public IEnumerable<PrebuiltEntityDto> GetList(Guid botId)
        {
            var bot = _botDomainService.Get(botId);
            if (bot ==null) throw new EntityNotFoundException(botId, typeof(Chatbot));
            List<PrebuiltEntityDto> result = new List<PrebuiltEntityDto>();
            var entityList = _entityDomainService.ListPrebuiltEntities(botId);
            IEnumerable<PrebuiltEntity> list = _prebuiltDomainService.List(bot.Language);
            foreach(var item in entityList)
            {
                var temp = new PrebuiltEntityDto()
                {
                    Id = item.Id,
                    Name = item.Name
                };
                var l = list.FirstOrDefault(n => n.Name == item.Name);
                if (l != null)
                {
                    temp.Description = l.Description;
                    temp.Example = string.IsNullOrEmpty(l.Example) ? new List<string>() : JsonConvert.DeserializeObject<List<string>>(l.Example);
                }
                result.Add(temp);
            }
            return result;
        }
    }
}
